package com.zj.inoutput.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步线程配置,使用方法：@Async("xxx") / 注入
 *
 * @author DuanYu <a>Email:z-houjie@qq.com</a>
 * @date 2022-02-08 11:13
 */

@EnableAsync
@Configuration
public class AsyncConfig {

    @Bean(name = "asyncOutput")
    public AsyncTaskExecutor asyncOutput() {
        return createThreadPoolTaskExecutor(4, 8, 100, "asyncOutput-");
    }

    @Bean(name = "asyncExecutor")
    public AsyncTaskExecutor asyncExecutor() {
        return createThreadPoolTaskExecutor(8, 16, 2000, "asyncExecutor-");
    }

    private ThreadPoolTaskExecutor createThreadPoolTaskExecutor(int core, int max, int queue, String threadNamePrefix) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(core);
        executor.setMaxPoolSize(max);
        executor.setQueueCapacity(queue);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadNamePrefix(threadNamePrefix);

        executor.setAwaitTerminationSeconds(100);
        executor.setKeepAliveSeconds(300);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
